'''
Created on 2012-5-29

@author: wb_suoyao.shen
'''
from django.db import models
from ssyblog.common import constant

class DiaryManager(models.Manager):
    def latest_diary(self):
        diary_list = self.raw('SELECT dd.id,dd.title,dd.author,dd.diary_tag,dd.summary,dd.content,dd.write_time FROM diary_diary dd ORDER BY write_time DESC LIMIT 1')
        if len(list(diary_list)) > 0:
            return diary_list[0]
        else:
            return None
    def current_diary(self):
        return self.order_by("-write_time")[0]
    def recently_diary(self):
        # recently diary list
        return self.order_by("-write_time")[:constant.recently_diary_number]
    def query_by_condition(self,title = '',diary_tag = '',startTime = None,endTime = None):
        q = []
        if title:
            q.append('models.Q(title__contains = title)')
        if diary_tag:
            q.append('models.Q(diary_tag__contains = diary_tag)')
        if startTime:
            q.append('models.Q(write_time__gte = startTime)')
        if endTime:
            q.append('models.Q(write_time__lte = endTime)')
        if q:
            qset = '&'.join(q)
            qset = 'qset=' + qset
            exec(qset)
            return self.filter(qset)
        else:
            return self.all()

class Diary(models.Model):
    title = models.CharField(max_length=256, null=True)
    author = models.CharField(max_length=256, null=True, blank=True)
    diary_tag = models.CharField(max_length=256, null=True)
    summary = models.CharField(max_length=2560, null=True)
    content = models.TextField(null=True, blank=True)
    write_time = models.DateTimeField(null=True, blank=True)
    modify_time = models.DateTimeField(null=True, blank=True)
    reply_count = models.IntegerField(blank=True, null=True)
    status = models.CharField(max_length=32, null=True, blank=True)  # 'on' and 'off'
    recommend = models.CharField(max_length=32,null=True,blank=True) # 'on' and 'off'
    objects = DiaryManager()
    
    def __unicode__(self):
        return self.title
    
    class Meta:
        ordering = ['-write_time']

    class Admin:
        list_display = ('title', 'author', 'diary_album','summary','content', 'write_time', 'recommend',)
        fields = (
            (None, {'fields': ('title', 'author', 'diary_album', 'summary', 'content','write_time','recommend')}),
        )
